/*
查找问题：线性、二分、插值、斐波那契、BST、哈希表...
二分查找 O(logN)
(1)数组必须有序的
(2)根据有序的方向 来进行元素的查询

*/
public class BinarySearch {
    public static void main(String[] args) {
        binarySearch01();
        binarySearch02();
    }

    private static void binarySearch02() {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int key = 1;
        int index = binarySearchRecursion(arr, 0, arr.length - 1, key);
        System.out.println(index);
    }

    private static int binarySearchRecursion(int[] arr, int l, int r, int key) {
        if (l > r) {
            return -1;
        }
        int m = (r - l) / 2 + l;
        if (arr[m] == key) {
            return m;
        }
        if (arr[m] < key) {
            return binarySearchRecursion(arr, m + 1, r, key);
        } else {
            return binarySearchRecursion(arr, l, m - 1, key);
        }
    }

    //二分查找迭代写法
    private static void binarySearch01() {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int min = 0;
        int max = arr.length - 1;
        int mid = (max - min) / 2 + min;
        int key = 12;
        while (arr[mid] != key) {
            if (arr[mid] < key) {
                min = mid + 1;
            } else {
                max = mid - 1;
            }
            if (min > max) {
                mid = -1;
                break;
            }
            mid = (max - min) / 2 + min;
        }
        System.out.println(mid);
    }
}






